﻿using Max.PH6_2009A.LowCode.DTO;
using Max.PH6_2009A.LowCode.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH6_2009A.LowCode.API.Controllers
{
    [Route("role")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        IRoleService _service;

        public RoleController(IRoleService service)
        {
            _service = service;
        }

        /// <summary>
        /// 角色查询
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get(string? name, int pageIndex = 1, int pageSize = 10)
        {
            ResponseResultDto dto = new();

            if (pageIndex <= 0) pageIndex = 1;
            if (pageSize <= 0) pageSize = 10;

            var data = _service.Select("select * from tb_role where name like @name", new { name = $"%{name}%" });

            int total = data.Count();
            data = data.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            dto.Data = new { items = data, total };
            return Ok(dto);
        }


        /// <summary>
        /// 添加角色的同时添加权限菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post(RoleInsertMenuDto dto)
        {
            ResponseResultDto result = new();

            if (string.IsNullOrEmpty(dto.RoleName))
            {
                result.Code = ResponseResultCode.RoleNameNull;
                result.Message = "角色名称不能为空";
                return BadRequest(result);
            }

            var data = _service.InsertRoleAndMenu(dto);

            if (!data.Item1)
            {
                result.Code = ResponseResultCode.RoleNameRepeat;
                result.Message = "角色名称已存在";
                return BadRequest(result);
            }

            return Ok(result);
        }

        /// <summary>
        /// 根据角色ID获取这个角色所拥有的权限菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("byid")]
        public IActionResult GetRoleMenuByRoleId(string roleId)
        {
            ResponseResultDto result = new();

            if (string.IsNullOrEmpty(roleId))
            {
                result.Code = ResponseResultCode.Failed;
                result.Message = "参数无效";
                return BadRequest(result) ;
            }   
            
            var data = _service.GetRoleMenuById(roleId);
            result.Data = data;
            return Ok(result);
        }
    }
}
